<template>
  <div class="cesium-3d-page">
    <!-- 顶部工具栏 -->
    <Toolbar 
      @resetCamera="cesiumUtils.resetCamera"
      @switchToSatellite="cesiumUtils.switchToSatellite"
      @switchToBaseMap="cesiumUtils.switchToBaseMap"
      @startAddingCamera="cameraMarkers.startAddingCamera"
      @testWVPConnection="testWVPConnection"
      @reloadWVPCameras="reloadWVPCameras"
      @showAllHiddenCameras="cameraMarkers.showAllHiddenCameras"
    />

    <!-- 3D视图容器 -->
    <div class="viewer-wrapper">
      <div ref="cesiumContainer" class="cesium-container"></div>
      
      <!-- 加载遮罩 -->
      <div v-if="isLoading" class="loading-mask">
        <div class="loading-spinner"></div>
        <p class="loading-text">{{ loadingText }}</p>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-toast">
        <div class="error-title">⚠️ 提示</div>
        <div class="error-content">{{ errorMessage }}</div>
        <button @click="cesiumUtils.clearError" class="close-btn">×</button>
      </div>
      
      <!-- 成功提示 -->
      <div v-if="successMessage" class="success-toast">
        <div class="success-title">✅ 成功</div>
        <div class="success-content">{{ successMessage }}</div>
        <button @click="cesiumUtils.clearSuccess" class="close-btn">×</button>
      </div>

      <!-- 选择位置提示 -->
      <div v-if="isAddingCameraMode && !showAddCameraDialog" class="position-select-tip">
        <div class="tip-content">
          <div class="tip-icon">🎯</div>
          <div class="tip-text">
            <strong>选择摄像头安装位置</strong>
            <p>请在3D场景中点击您想要安装摄像头的位置</p>
          </div>
          <button @click="cameraMarkers.cancelAddCamera" class="tip-cancel">取消</button>
        </div>
      </div>

      <!-- 摄像头信息框 -->
      <CameraInfoBox
        :showCameraInfo="showCameraInfo"
        :selectedCamera="selectedCamera"
        @close="cameraMarkers.closeCameraInfo"
        @flyToCamera="cameraMarkers.flyToCamera"
        @openVideoPlayer="videoPlayer.openVideoPlayer"
      />
    </div>

    <!-- 右侧摄像头面板 -->
    <CameraPanel
      :isPanelCollapsed="isPanelCollapsed"
      :cameraList="cameraList3D"
      :selectedCamera="selectedCamera"
      @togglePanel="cameraMarkers.togglePanel"
      @selectCamera="cameraMarkers.selectCamera"
      @flyToCamera="cameraMarkers.flyToCamera"
      @openVideoPlayer="videoPlayer.openVideoPlayer"
    />

    <!-- 视频播放弹窗 -->
    <VideoPlayerModal
      ref="videoPlayerModalRef"
      v-model:showVideoPlayer="showVideoPlayer"
      :selectedCamera="currentCamera"
      :streamInfo="streamInfo"
      @close="videoPlayer.closeVideoPlayer"
    />

    <!-- 新增摄像头对话框 -->
    <AddCameraModal
      :showAddCameraDialog="showAddCameraDialog"
      :selectedPosition="selectedPosition"
      :newCameraForm="newCameraForm"
      :nameCheckMessage="nameCheckMessage"
      :canSaveCamera="canSaveCamera"
      :isAddingCamera="isAddingCamera"
      :isEditingCamera="isEditingCamera"
      @cancel="cameraMarkers.cancelAddCamera"
      @confirm="cameraMarkers.confirmAddCamera"
      @checkName="cameraMarkers.checkCameraNameUnique"
      @updateForm="cameraMarkers.updateCameraForm"
    />

    <!-- 摄像头右键菜单 -->
    <CameraContextMenu
      :show="showContextMenu"
      :position="contextMenuPosition"
      :camera="contextMenuCamera"
      :hiddenCameras="hiddenCameras"
      @playVideo="cameraMarkers.playVideo"
      @focusCamera="cameraMarkers.focusOnCamera"
      @editCamera="cameraMarkers.editCamera"
      @toggleVisibility="cameraMarkers.toggleCameraVisibility"
      @deleteCamera="cameraMarkers.deleteCamera"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useCesium } from './composables/useCesium'
import { useCameraMarkers } from './composables/useCameraMarkers'
import { useVideoPlayer } from './composables/useVideoPlayer'
import { useCameraStore } from '@/store/modules/camera'
import Toolbar from './components/Toolbar.vue'
import CameraInfoBox from './components/CameraInfoBox.vue'
import CameraPanel from './components/CameraPanel.vue'
import VideoPlayerModal from './components/VideoPlayerModal.vue'
import AddCameraModal from './components/AddCameraModal.vue'
import CameraContextMenu from './components/CameraContextMenu.vue'

// 使用组合式函数
const cesiumUtils = useCesium()
const videoPlayer = useVideoPlayer(cesiumUtils)
const cameraMarkers = useCameraMarkers(cesiumUtils, videoPlayer)
const cameraStore = useCameraStore()

// 解构响应式数据以便在模板中使用
const {
  showCameraInfo,
  selectedCamera,
  isPanelCollapsed,
  cameraList3D,
  showAddCameraDialog,
  isAddingCameraMode,
  selectedPosition,
  newCameraForm,
  nameCheckMessage,
  canSaveCamera,
  isAddingCamera,
  showContextMenu,
  contextMenuPosition,
  contextMenuCamera,
  isEditingCamera,
  hiddenCameras
} = cameraMarkers

const {
  showVideoPlayer,
  streamInfo,
  currentCamera
} = videoPlayer

const {
  isLoading,
  loadingText,
  errorMessage,
  successMessage
} = cesiumUtils

// 模板引用
const cesiumContainer = cesiumUtils.cesiumContainer
const videoPlayerModalRef = ref(null)

// 将VideoPlayerModal的cusPlayerRef传递给videoPlayer
const cusPlayerRef = computed(() => {
  const modalRef = videoPlayerModalRef.value
  const playerRef = modalRef?.cusPlayerRef
  console.log('计算cusPlayerRef:', { modalRef, playerRef })
  return playerRef
})
videoPlayer.cusPlayerRef = cusPlayerRef

// 初始化应用
const initializeApp = async () => {
  try {
    console.log('开始初始化3D应用...')
    
    // 初始化Cesium
    console.log('正在初始化Cesium...')
    await cesiumUtils.initCesium()
    console.log('Cesium初始化完成')
    
    // 设置摄像头点击事件
    console.log('设置摄像头点击事件...')
    cameraMarkers.setupCameraClickEvents()
    console.log('摄像头点击事件设置完成')
    
    // 从API加载摄像头数据并添加标记
    console.log('开始加载摄像头数据...')
    const cameras3D = await cameraMarkers.loadCamerasFromAPI()
    console.log('摄像头数据加载完成，开始添加标记...')
    cameraMarkers.addCameraMarkers(cameras3D)
    console.log('摄像头标记添加完成')
    
    console.log('3D应用初始化完成')
  } catch (error) {
    console.error('3D应用初始化失败:', error)
    cesiumUtils.showError('应用初始化失败: ' + error.message)
  }
}

// 全局函数（供HTML描述中的按钮调用）
window.focusCamera = (cameraId) => {
  const camera = cameraList3D.value.find(c => c.id === cameraId)
  if (camera) {
    cameraMarkers.flyToCamera(camera)
  }
}

window.openVideoPlayer = (cameraId) => {
  const camera = cameraList3D.value.find(c => c.id === cameraId)
  if (camera) {
    videoPlayer.openVideoPlayer(camera)
  }
}

// 测试WVP连接
const testWVPConnection = async () => {
  try {
    console.log('手动测试WVP连接...')
    cesiumUtils.isLoading.value = true
    cesiumUtils.loadingText.value = '正在测试WVP连接...'
    
    const result = await cameraStore.testWVPConnection()
    console.log('WVP连接测试成功:', result)
    cesiumUtils.showSuccess('WVP连接测试成功！')
  } catch (error) {
    console.error('WVP连接测试失败:', error)
    cesiumUtils.showError('WVP连接测试失败: ' + error.message)
  } finally {
    cesiumUtils.isLoading.value = false
  }
}

// 重新加载WVP摄像头数据
const reloadWVPCameras = async () => {
  try {
    console.log('手动重新加载WVP摄像头数据...')
    cesiumUtils.isLoading.value = true
    cesiumUtils.loadingText.value = '正在重新加载摄像头数据...'
    
    // 清除现有摄像头标记
    cameraMarkers.clearAllCameraMarkers()
    
    // 重新加载摄像头数据
    const cameras3D = await cameraMarkers.loadCamerasFromAPI()
    cameraMarkers.addCameraMarkers(cameras3D)
    
    console.log('摄像头数据重新加载完成')
    cesiumUtils.showSuccess(`摄像头数据重新加载完成！共加载 ${cameras3D.length} 个摄像头`)
  } catch (error) {
    console.error('重新加载摄像头数据失败:', error)
    cesiumUtils.showError('重新加载摄像头数据失败: ' + error.message)
  } finally {
    cesiumUtils.isLoading.value = false
  }
}

// 生命周期
onMounted(async () => {
  await nextTick()
  
  // 等待容器准备好
  setTimeout(async () => {
    if (cesiumContainer.value) {
      await initializeApp()
    }
  }, 100)
  
  // 添加全局点击事件来隐藏右键菜单
  document.addEventListener('click', cameraMarkers.hideContextMenu)
  
  // 禁用整个页面的右键菜单（仅在Cesium容器区域）
  const cesiumElement = cesiumContainer.value
  if (cesiumElement) {
    cesiumElement.addEventListener('contextmenu', (e) => {
      e.preventDefault()
      return false
    })
  }
})

onUnmounted(() => {
  // 清理视频播放器
  videoPlayer.cleanup()
  
  // 清理Cesium viewer
  cesiumUtils.cleanup()
  
  // 清理全局函数
  delete window.focusCamera
  delete window.openVideoPlayer
  
  // 移除全局点击事件
  document.removeEventListener('click', cameraMarkers.hideContextMenu)
  
  // 移除右键菜单禁用
  const cesiumElement = cesiumContainer.value
  if (cesiumElement) {
    cesiumElement.removeEventListener('contextmenu', (e) => {
      e.preventDefault()
      return false
    })
  }
})
</script>

<style lang="scss" scoped>
.cesium-3d-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  overflow: hidden;
}

.viewer-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  min-height: 0;
}

.cesium-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;

  .loading-spinner {
    width: 48px;
    height: 48px;
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-top: 4px solid #3b82f6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }

  .loading-text {
    color: white;
    font-size: 16px;
    margin: 0;
  }
}

.error-toast {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(255, 193, 7, 0.95);
  color: #333;
  padding: 15px;
  border-radius: 8px;
  max-width: 400px;
  z-index: 2000;
  border-left: 4px solid #ff9800;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);

  .error-title {
    font-weight: bold;
    margin-bottom: 8px;
    font-size: 14px;
  }

  .error-content {
    font-size: 13px;
    line-height: 1.4;
    margin-bottom: 8px;
  }

  .close-btn {
    background: none;
    border: none;
    color: #333;
    font-size: 18px;
    cursor: pointer;
    position: absolute;
    top: 8px;
    right: 8px;
  }
}

.success-toast {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(40, 167, 69, 0.95);
  color: white;
  padding: 15px;
  border-radius: 8px;
  max-width: 400px;
  z-index: 2000;
  border-left: 4px solid #28a745;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);

  .success-title {
    font-weight: bold;
    margin-bottom: 8px;
    font-size: 14px;
  }

  .success-content {
    font-size: 13px;
    line-height: 1.4;
    margin-bottom: 8px;
  }

  .close-btn {
    background: none;
    border: none;
    color: white;
    font-size: 18px;
    cursor: pointer;
    position: absolute;
    top: 8px;
    right: 8px;
  }
}

.position-select-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2500;
  pointer-events: none;

  .tip-content {
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 20px 24px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    gap: 16px;
    min-width: 400px;
    pointer-events: auto;

    .tip-icon {
      font-size: 32px;
      flex-shrink: 0;
    }

    .tip-text {
      flex: 1;

      strong {
        display: block;
        font-size: 16px;
        margin-bottom: 4px;
        color: #fbbf24;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: #d1d5db;
        line-height: 1.4;
      }
    }

    .tip-cancel {
      background: #ef4444;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 6px;
      font-size: 14px;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background: #dc2626;
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 全局Cesium样式修复
:global(.cesium-widget) {
  width: 100% !important;
  height: 100% !important;
}

:global(.cesium-widget canvas) {
  width: 100% !important;
  height: 100% !important;
}

:global(.cesium-viewer) {
  width: 100% !important;
  height: 100% !important;
  font-family: inherit;
}

:global(.cesium-viewer-cesiumWidgetContainer) {
  width: 100% !important;
  height: 100% !important;
}

:global(.cesium-viewer-toolbar) {
  top: 10px;
  right: 10px;
  left: auto;
}
</style>